﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Windows.Forms;
using NDK.LocalUtils;
using NDK.Module.DAL;
using NDK.Module.Model;
using NDK.Utils;

namespace NDK.Frm
{
    public partial class Dlg_AutoCompensation : Form
    {
        private static log4net.ILog m_Logger = log4net.LogManager.GetLogger("Dlg_AutoCompensation");
        DataTable dt = new DataTable();
        DataTable dt_Offset = new DataTable();
        string tempPath = Common.pointCheckEncrypterPath + @"\temp.rs";
        string filePath = "";
        MeasureSizeServices measureSizeServices = new MeasureSizeServices();
        public Dlg_AutoCompensation()
        {
            InitializeComponent();
        }

        private void Dlg_AutoCompensation_Load(object sender, EventArgs e)
        {
            try
            {
                //第一步：读取点检数据，并显示到界面
                string path = Common.pointCheckEncrypterPath;
                OpenFileDialog fileDialog = new OpenFileDialog();
                fileDialog.Multiselect = true;
                fileDialog.InitialDirectory = path;
                fileDialog.Title = "请选择点检文件";
                fileDialog.Filter = "点检文件(*.rs)|*.rs";
                if (fileDialog.ShowDialog() == DialogResult.OK)
                {
                    filePath = fileDialog.FileName;
                    string strEncrypt = string.Empty;
                    string strDecrypt = string.Empty;
                    string strLine = "";
                    //逐行读取并解密加密文件
                    System.Text.Encoding encoding = Encoding.GetEncoding(0);
                    System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open,
                        System.IO.FileAccess.Read);

                    System.IO.StreamReader sr = new System.IO.StreamReader(fs, encoding);
                    while ((strLine = sr.ReadLine()) != null && strLine != "")
                    {
                        strDecrypt += (StringEncryptUtils.Decrypt(strLine.Replace(Environment.NewLine, "")) + Environment.NewLine);
                    }
                    sr.Close();
                    fs.Close();
                    FileUtils.AppendText(tempPath, strDecrypt);//将解密后的字符串写到临时文件

                    dt = FileUtils.OpenCSV(tempPath);//将解密内容显示到界面
                    FileUtils.DeleteFile(tempPath);
                    dgv_AutoCompensation.DataSource = null;
                    dgv_AutoCompensation.DataSource = dt;

                    //第二步：读取标准块数据，并显示到界面,同时将尺寸名称存到一个存放Offset的DataTable表里面
                    List<MeasureSize> measureSizeList = measureSizeServices.GetAllByProjectNameAndTurnNum(Common.ProjectName, 0);
                    DataRow dr_Nom = dt.Rows.Add();
                    dr_Nom["Time"] = "\\";
                    dr_Nom["Position"] = "\\";
                    dr_Nom["Line"] = "\\";
                    dr_Nom["MeasureId"] = "\\";
                    dr_Nom["OK_NG"] = "\\";
                    dr_Nom["NG_FAI"] = "\\";
                    dr_Nom["Barcode"] = "Nom";
                    int indexNom = dt.Rows.IndexOf(dr_Nom);
                    foreach (MeasureSize size in measureSizeList)
                    {
                        if (size.IsShow == false)
                        {
                            continue;
                        }
                        try
                        {
                            dr_Nom[size.SizeName] = size.NormValue;
                        }
                        catch { }
                    }

                    //第三步：计算Offset并显示到界面,超过两条显示红色,同时将尺寸Offset存到一个的DataTable表里面
                    for (int i = 0; i < indexNom; i++)
                    {
                        DataRow dr_Offset = dt.Rows.Add();
                        dr_Offset["Time"] = "\\";
                        dr_Offset["Position"] = "\\";
                        dr_Offset["Line"] = "\\";
                        dr_Offset["OK_NG"] = "\\";
                        dr_Offset["NG_FAI"] = "\\";
                        int indexOffset = dt.Rows.IndexOf(dr_Offset);
                        dr_Offset["Barcode"] = "(Measured" + (i + 1) + "-Nom)";

                        dr_Offset["MeasureId"] = ((i + 1).ToString());
                        foreach (MeasureSize size in measureSizeList)
                        {
                            try
                            {
                                if (size.IsShow == false)
                                {
                                    continue;
                                }
                                double offset1 = double.Parse(dt.Rows[indexOffset - indexNom - 1][size.SizeName].ToString()) - size.NormValue;
                                dr_Offset[size.SizeName] = offset1.ToString("0.0000");
                            }
                            catch { }

                        }
                    }

                    dgv_AutoCompensation.DataSource = null;
                    dgv_AutoCompensation.DataSource = dt;













                    //第二步：读取标准块数据，并显示到界面,同时将尺寸名称存到一个存放Offset的DataTable表里面
                    //List<MeasureSize> measureSizeList = measureSizeServices.GetAllByProjectNameAndTurnNum(Common.ProjectName, 0);

                    //int index = dgv_AutoCompensation.Rows.Add();
                    //dgv_AutoCompensation.Rows[index].Cells["Dim"].Value = "Nom";
                    //List<string> hearderList = new List<string>();
                    //hearderList.Add("Dim");
                    //foreach (MeasureSize size in measureSizeList)
                    //{
                    //    hearderList.Add(size.SizeName);
                    //    dgv_AutoCompensation.Rows[index].Cells[size.SizeName].Value = size.NormValue;
                    //    dgv_AutoCompensation.Rows[index].Cells[size.SizeName].Style.ForeColor = Color.Green;
                    //}
                    //dt_Offset.Rows.Add(hearderList.ToArray());

                    ////第三步：计算Offset并显示到界面,超过两条显示红色,同时将尺寸Offset存到一个的DataTable表里面
                    //for (int i = 0; i < 8; i++)
                    //{
                    //    index = dgv_AutoCompensation.Rows.Add();
                    //    dgv_AutoCompensation.Rows[index].Cells["Dim"].Value = "(Measured" + (i + 1) + "-Nom)";
                    //    List<string> valueList = new List<string>();
                    //    valueList.Add((i + 1).ToString());
                    //    foreach (MeasureSize size in measureSizeList)
                    //    {
                    //        double offset1 = double.Parse(dt.Rows[0][size.SizeName].ToString()) - size.NormValue;
                    //        dgv_AutoCompensation.Rows[index].Cells[size.SizeName].Value = offset1;
                    //        if (Math.Abs(offset1) > 0.02)
                    //        {
                    //            dgv_AutoCompensation.Rows[index].Cells[size.SizeName].Style.ForeColor = Color.Red;
                    //        }
                    //        valueList.Add(offset1.ToString());
                    //    }
                    //    dt_Offset.Rows.Add(valueList.ToArray());
                    //    valueList = null;
                    //}
                }
            }
            catch (Exception ex)
            {
                m_Logger.Error(ex.StackTrace);
                MessageBox.Show("操作点检文件失败！");
            }
        }

        private void btn_ConfirmCompensation_Click(object sender, EventArgs e)
        {
            FileUtils.SaveCSV(dt, Common.dataSavePath + @"\Offset" + DateTime.Now.ToString("yyyy-MM-dd") + ".csv");
            //FileUtils.SaveCSV(dt_Offset, Common.dataSavePath + @"\Offset" + DateTime.Now.ToString("yyyy-MM-dd") + ".csv");
            //List<MeasureSize> measureSizeList = new List<MeasureSize>();
            //for (int nest = 0; nest < 8; nest++)
            //{
            //    measureSizeList = measureSizeServices.GetAllByProjectNameAndTurnNum(Common.ProjectName, nest);
            //    foreach (var measureSize in measureSizeList)
            //    {
            //        measureSize.B -= double.Parse(dt_Offset.Rows[nest][measureSize.SizeName].ToString());
            //        measureSizeServices.Update(measureSize);
            //    }
            //}
        }
    }
}

